package com.base.core.mvc.web;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.servlet.ModelAndView;

import com.base.core.context.mvc.BaseV1Controller;
import com.base.core.head.ao.PageAO;
import com.base.core.head.utils.DataDictionaryUtils;
import com.base.core.mvc.business.CommonBusiness;
import com.gitee.magic.framework.head.utils.TimeUtils;
import com.gitee.magic.framework.head.vo.QueryVO;

/**
 * @author start
 */
public class BaseWebController extends BaseV1Controller {
	
	@InitBinder
	public void initBinder(ServletRequestDataBinder bin) {
		SimpleDateFormat sdf = new SimpleDateFormat(TimeUtils.YYYYMMDDHHMMSS_F);
		CustomDateEditor cust = new CustomDateEditor(sdf, true);
		bin.registerCustomEditor(Date.class, cust);
	}

	private <T>ModelAndView responseWrapper(Object ao,QueryVO<T> vo,String viewName){
		ModelAndView view=new ModelAndView();
		view.addObject("ao", ao);
		if(vo==null) {
			vo=new QueryVO<>();
			vo.setTotal(0);
		}
		view.addObject("vo", vo);
		view.setViewName(viewName);
		return view;
	}
	
	protected <P extends PageAO,T>ModelAndView response(P ao,QueryVO<T> vo,String viewName){
		return responseWrapper(ao,vo,viewName);
	}
	
	protected <P extends Map<String,Object>,T>ModelAndView response(P ao,QueryVO<T> vo,String viewName){
		return responseWrapper(ao,vo,viewName);
	}
	
	////////////////////////////////////////////////////////////////////////
	
	protected <P extends PageAO,T>ModelAndView response(P ao,QueryVO<T> vo){
		return response(ao,vo,request.getRequestURI());
	}
	
	protected <P extends Map<String,Object>,T>ModelAndView response(P ao,QueryVO<T> vo){
		return response(ao,vo,request.getRequestURI());
	}
	
	protected <P extends Map<String,Object>,T>ModelAndView response(ModelAndView view){
		view.setViewName(request.getRequestURI());
		return view;
	}
	
	protected void addRequestAttribute(ModelAndView view) {
		view.addObject("dict",DataDictionaryUtils.getAllDataDictionary());
	}
	
	protected void addRequestAttributeEnum(ModelAndView view,Class<?>... enums) {
		for(Class<?> e:enums) {
			view.addObject(e.getSimpleName(),CommonBusiness.getEnumMap(e));
		}
	}
	
}
